<template>
    <MainPage activeMenu=""> 
        <el-container>
            <el-main>
                <div class="shoppingCart">
                    <el-card class="shopping_card">
                        <div class="title">
                            <span>购物车</span>
                            <i class="el-icon-shopping-cart-full"></i>
                        </div>
                        <el-table class="shopping_table" :data="cartItems" border style="width: 100%" @selection-change="selectChange">
                            <el-table-column type="selection" label="全部" width="80" align="center"></el-table-column>
                            <el-table-column prop="name" label="商品名称" width="200" align="center"></el-table-column>
                            <el-table-column prop="cover" label="商品" width="150" align="center">
                                <template #default="{ row }">
                                    <img :src="row.cover" alt="图片加载错误" class="cover">
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="单价（元）" width="120" align="center"></el-table-column>
                            <el-table-column prop="number" label="数量" width="120" align="center"></el-table-column>
                            <el-table-column prop="totalPrice" label="实付款（元）" width="150" align="center">
                                <template #default="{ row }">
                                    {{ row.number * row.price }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="date" label="操作" width="150" align="center">
                                <template #default="{ row }">
                                    <el-button type="primary" @click="detail(row)">详情</el-button>
                                    <el-tooltip effect="light" content="删除商品" placement="right">
                                        <el-button type="danger" @click="confirmDelete(row)"><el-icon><Delete /></el-icon></el-button>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="bottom">
                            <span class="tips">已选择{{ selectedCount }}件商品&nbsp;&nbsp;&nbsp;实付款：{{ totalPrice }}元</span>
                            <el-button type="success" plain @click="pay">结算</el-button>
                        </div>
                    </el-card>
                </div>
         </el-main>
        </el-container>
    </MainPage>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from '../../../axios/axios';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import MainPage from '../../Component/MainPage.vue';

export default {
    name: 'ShoppingCart',
    components: {
        MainPage,
    },
    setup() {
        const router = useRouter();

        const cartItems = ref([]);
        const selectedBooks = ref([]);
        const selectedCount = ref(0);
        const totalPrice = ref(0);

        const fetchCart = async () => {
            try {
                const carts = await axios.get('/carts/my-cart');

                if (!Array.isArray(carts)) {
                    throw new Error('Expected an array of cart items');
                }

                const productDetailsPromises = carts.map(cartItem =>
                    axios.get(`/product/${cartItem.productId}`)
                );

                const imagePromises = carts.map(cartItem =>
                    axios.get(`/product/${cartItem.productId}/image`, { responseType: 'blob' })
                );

                const productDetailsResponses = await Promise.all(productDetailsPromises);
                const imagesResponses = await Promise.all(imagePromises);

                const products = productDetailsResponses;
                const images = imagesResponses.map(response => URL.createObjectURL(response));

                cartItems.value = carts.map((cartItem, index) => ({
                    ...cartItem,
                    cover: images[index], // Use the image URL
                    price: products[index].price,
                    number: cartItem.count,
                    name: products[index].name, // Assuming name is the product name
                }));

                calculateTotal();
            } catch (error) {
                console.error('Error fetching cart:', error.message);
                ElMessage({
                    type: 'error',
                    message: '获取购物车信息失败，请稍后再试'
                });
            }
        };

        const selectChange = (selection) => {
            selectedBooks.value = selection;
            selectedCount.value = selection.length;
            calculateTotal();
        };

        const calculateTotal = () => {
            let sum = 0;
            selectedBooks.value.forEach(item => {
                sum += item.number * item.price;
            });
            totalPrice.value = sum;
        };

        const confirmDelete = (book) => {
            ElMessageBox.confirm(
                '确定要删除该商品吗?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                deleteBook(book);
            }).catch(() => {
                // User canceled the deletion
            });
        };

        const deleteBook = async (book) => {
            try {
                await axios.delete(`/carts/my-cart/delete/${book.cartsId}`);
                fetchCart(); // Refresh cart after deletion
            } catch (error) {
                console.error('Error deleting book:', error.message);
                ElMessage({
                    type: 'error',
                    message: '删除商品失败，请稍后再试'
                });
            }
        };

        const detail = (book) => {
            router.push({ path: '/book', query: { id: book.id } }); // Pass the book ID to the route
        };

        const pay = () => {
            if (selectedCount.value === 0) {
                ElMessage({
                    type: 'info',
                    message: '请选择要结算的商品'
                });
                return;
            }
            ElMessage({
                type: 'success',
                message: `结算成功！共支付${totalPrice.value}元`
            });
            // Optionally handle payment logic here and refresh cart after payment
            fetchCart();
        };

        onMounted(() => {
            fetchCart();
        });

        return {
            cartItems,
            selectedCount,
            totalPrice,
            selectChange,
            confirmDelete,
            deleteBook,
            detail,
            pay
        };
    }
};
</script>

<style scoped>
.shoppingCart {
    display: flex;
    justify-content: center;
    text-align: center;
    background-color: #eee;
}

.shopping_card {
    margin: 30px 0px;
    width: 1000px;
}

.title {
    font-size: 15px;
    font-weight: 900;
    padding-left: 10px;
    padding-bottom: 10px;
    text-align: left;
}

.cover {
    width: 100px;
    height: 100px;
}

.bottom {
    margin-top: 20px;
    text-align: right;
}

.tips {
    font-size: 20px;
    padding-right: 30px;
}
</style>



